package com.zh.chat;

import io.grpc.stub.StreamObserver;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author Zhou
 * @date 13:23 2025/4/21
 */
public class ChatServiceImpl extends ChatServiceGrpc.ChatServiceImplBase {

    @Override
    public void getChatOfflineList(ChatProto.ChatMsgReq request, StreamObserver<ChatProto.ChatMsgListResp> responseObserver) {
        var response = ChatProto.ChatMsgListResp.newBuilder()
                .addAllList(messages)
                .build();
        // 发送响应消息
        responseObserver.onNext(response);
        // 标记流结束
        responseObserver.onCompleted();
    }

    static List<ChatProto.ChatMsg> messages = new ArrayList<>(30);

    static {
        for (int i = 0; i < 23; i++) {
            var chatMsg = ChatProto.ChatMsg.newBuilder()
                    .setReceiver("aa")
                    .setSender("bb")
                    .setContent("Sample message")
                    .setType(1)
                    .setUrlRef(false)
                    .setStatus(200)
                    .setChatId("chat-1")
                    .setConvId(1)
                    .setId(1)
                    .setCreateTime(java.time.Instant.now().toString())
                    .build();

            messages.add(chatMsg);
        }

    }

    @Override
    public void streamChatOfflineList(ChatProto.ChatMsgReq request, StreamObserver<ChatProto.ChatMsgListResp> responseObserver) {
        // 模拟根据请求生成响应
        var size = 5;
        // 模拟根据请求生成多个响应
        for (int i = 1; ; i++) {
            var offset = (i - 1) * size;
            if (offset >= messages.size()) {
                break;
            }
            var end = Math.min(offset + size, messages.size());

            // 获取第3到第8个元素（索引2至7）
            var part = messages.subList(offset, end);

            // 发送响应消息到客户端
            var response = ChatProto.ChatMsgListResp.newBuilder()
                    .addAllList(part)
                    .build();
            // 发送响应消息
            responseObserver.onNext(response);
            // 模拟发送间隔
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }

        // 标记流结束
        responseObserver.onCompleted();
    }
}
